package com.yonyouup.ucostcontrol.expression;
import java.util.*;

public class CalculatorHelper {
	
	private static Set<String> numberOperators = new HashSet<>();
	private static Set<String> logicOperators = new HashSet<>();
	private static Set<String> singleOperators = new HashSet<>();
	private static Set<String> commonOperators = new HashSet<>();
	
	static{
		numberOperators.add("+");
		numberOperators.add("-");
		numberOperators.add("*");
		numberOperators.add("/");
		numberOperators.add(">");
		numberOperators.add(">=");
		numberOperators.add("<");
		numberOperators.add("<=");
		
		
		logicOperators.add("&");
		logicOperators.add("|");
		
		
		commonOperators.add("==");
		commonOperators.add("!=");
		
		singleOperators.add("!");
	}
	
	/**
	 * 双目运算符计算
	 * @param left
	 * @param right
	 * @param operator + - * \/ & |  > < == != >= <=
	 * @return
	 */
	public static Object calculate(Object left, Object right, String operator) {
		if (commonOperators.contains(operator)){
			if (operator.equals("==")){
				return left.equals(right);
			}
			else if (operator.equals("!=")){
				return !left.equals(right);
			}
		}
		
		if (numberOperators.contains(operator)){
			Double dLeft = Double.valueOf(left.toString());
			Double dRight = Double.valueOf(right.toString());
			if (operator.equals("+")){
				return dLeft + dRight;
			}
			else if (operator.equals("-")){
				return dLeft - dRight;
			}
			else if (operator.equals("*")){
				return dLeft * dRight;
			}
			else if (operator.equals("/")){
				return dLeft / dRight;
			}
			else if (operator.equals(">")){
				return dLeft > dRight;
			}
			else if (operator.equals(">=")){
				return dLeft >= dRight;
			}
			else if (operator.equals("<")){
				return dLeft < dRight;
			}
			else if (operator.equals("<=")){
				return dLeft <= dRight;
			}
		}
		
		if (logicOperators.contains(operator)){
			Boolean bLeft = Boolean.valueOf(left.toString());
			Boolean bRight = Boolean.valueOf(right.toString());
			if (operator.equals("&")){
				return bLeft && bRight;
			}
			else if (operator.equals("|")){
				return bLeft || bRight;
			}
		}
		
		
		throw new ExpressionException("invalid operator : " + operator, null);
	}

	/**
	 * 单目运算符计算
	 * @param value
	 * @param operator !
	 * @return
	 */
	public static Object calculate(Object value, String operator) {
		if (singleOperators.contains(operator)){
			if (operator.equals("!")){
				boolean bValue = (boolean)value;
				return !bValue;
			}
			
		}
		throw new ExpressionException("invalid operator : " + operator, null);
	}
	
	/**
	 * 三目运算符
	 * @param value1
	 * @param value2
	 * @param value3
	 * @param operator 其实可以忽略， 肯定是：
	 * @return
	 */
	public static Object calculate(Object value1, Object value2, Object value3, String operator){
		Boolean flag = Boolean.parseBoolean(value1.toString());
		return flag ? value2 : value3;
	}
}

